<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/5/3
 * Time: 下午5:16
 */

namespace common\service;

use common\jobs\IssueCouponsJob;
use common\models\Activity;
use common\models\Groupbuy;
use common\models\Product;
use yii;
use common\models\User;
use common\models\CouponCategory;
/**
 * Class GroupbuyService
 * @package common\service
 * @SuppressWarnings(PHPMD)
 */
class GroupbuyService
{
    //开团接口
     public function startGroup($product_id,$activity_id){
         //初始化变量
         $userid=Yii::$app->user->id;
         if(empty($product_id) || empty($activity_id)){
             return ['code'=>-1,'message'=>'参数不正确'];
         }
        //商品信息检测
         $product = Product::findOne($product_id)->getAttributes(explode(",","id,ttid,name,remark,notes,image,coupon_id,newprice,price,share_title,share_img,share_txt,share_url,description"));
         if(empty($product)){
             return ['code'=>-2,'message'=>'商品不存在'];
         }

         //是否参加过
         $isJoin = false;

         $goodsGroup = GroupBuy::find()->where(['user1'=>$userid])->all();
         if($goodsGroup){
             foreach($goodsGroup as $group){
                 $users = $group->users;
                 $users = json_decode($users);
                 foreach($users as $user){
                     if($user->id==$userid){
                         $isJoin = true;
                         $joinGroup=$group;
                     }
                 }
             }
         }
        if(!$isJoin){

             $goodsGroup = GroupBuy::find()->Where('goodsid='.$product['id'].' and user1<>'.$userid)->all();
             if($goodsGroup){
                 foreach($goodsGroup as $group){
                     $users = $group->users;
                     $users = json_decode($users);
                     foreach($users as $user){
                         if($user->id==$userid){
                             $isJoin = true;
                             $joinGroup=$group;
                             break;

                         }
                     }
                     if($isJoin){break;}
                 }
             }



         }
         if($isJoin){
             return ['code'=>-3,'message'=>'已经参加过不允许参加','data'=>['group_id'=>$joinGroup->id]];
         }
         //查看优惠券还有没有
         $couponcategory = CouponCategory::findOne($product['coupon_id']);
         if(!$this->couponifexist($couponcategory->mark_id)){
             return ['code'=>-6,'message'=>'优惠券已发完'];
         }
         unset($product['coupon_id']);
         //是否符合配置条件
        //读取配置
//         $setting = Activity::find()->where('status==1 and goods REGEXP \'^([1234567890]+,){0,}'.$product_id.'(,[1234567890]+){0,}$\'')->one();
         $setting = Activity::findOne($activity_id);
         $start_user_type=$setting->start_user_type;
         $start_time=$setting->start_time;
         $end_time = $setting->end_time;

         if(time()<strtotime($start_time) || time()>strtotime($end_time)){
             return ['code'=>-4,'message'=>'不在活动时间'];
         }
         //设置新用户时候领过券的不能发
         if($start_user_type==1 && Yii::$app->user->identity->status==1){
             return ['code'=>-5,'message'=>'本活动老用户不能发起'];
         }
         // 设置老用户的时候未领过券的不能发
         if($start_user_type==2 && Yii::$app->user->identity->status==0){
             return ['code'=>-5,'message'=>'本活动新用户不能发起'];
         }
         //入库
        $model= new Groupbuy();
         $model->user1=$userid;
         $users = User::findOne($userid)->getAttributes(['id','nickname','avatar','phone']);
         $users['captain']=true;
         $model->users=json_encode([$users]);
         $model->goodsid=$product_id;
         $model->createtime=date("Y-m-d H:i:s");
         $model->status=0;
         //返回结果
         if($model->save()){
             return ['code'=>1,'message'=>'success','data'=>[
                 'id'=>$model->id,
                 'status'=>$model->status,
                 'product'=>$product,
                 'members'=>json_decode($model->users,true)
                 ]];
         }else{
             return ['code'=>0,'message'=>$model->getErrors()];
         }

     }
    //参团接口
    public function joinGroup($group_id){
        //初始化变量
        $userid=Yii::$app->user->id;
        //是否参加过
        $isJoin = false;
        $groupbuy = GroupBuy::findOne($group_id);
        if(empty($groupbuy)){
            return ['code'=>-1,'message'=>'参加的团不存在'];
        }
        if($groupbuy->status==1){
            return ['code'=>-2,'message'=>'已满团'];
        }


        $goodsGroup = GroupBuy::find()->all();
        if($goodsGroup){
            foreach($goodsGroup as $group){
                $users = $group->users;
                $users = json_decode($users);
                foreach($users as $user){
                    if($user->id==$userid){
                        $isJoin = true;
                        $joinGroup=$group;
                    }
                }
            }
        }

        if($isJoin){
            return ['code'=>-3,'message'=>'已经参加过不允许参加','data'=>['group_id'=>$joinGroup->id]];
        }
        //查看优惠券还有没有
        $product=Product::findOne($groupbuy->goodsid);
        $couponcategory = CouponCategory::findOne($product->coupon_id);
        if(!$this->couponifexist($couponcategory->mark_id)){
            return ['code'=>-7,'message'=>'优惠券已发完'];
        }
        //是否符合配置条件
        //读取配置
        $setting = Activity::find()->where('goods REGEXP \'^([1234567890]+,){0,}'.$groupbuy->goodsid.'(,[1234567890]+){0,}$\'')->one();
        $join_user_type=$setting->join_user_type;
        $start_time=$setting->start_time;
        $end_time = $setting->end_time;
        $peoples = $setting->peoples;
        if(time()<strtotime($start_time) || time()>strtotime($end_time)){
            return ['code'=>-4,'message'=>'不在活动时间'];
        }
        //设置新用户时候领过券的不能发
        if($join_user_type==1 && Yii::$app->user->identity->status==1){
            return ['code'=>-5,'message'=>'本活动老用户不能参加'];
        }
        // 设置老用户的时候未领过券的不能发
        if($join_user_type==2 && Yii::$app->user->identity->status==0){
            return ['code'=>-5,'message'=>'本活动新用户不能参加'];
        }
        //入库
        $model= GroupBuy::findOne($group_id);
        $users = json_decode($model->users,true);

        if(count($users)>=$peoples){
            return ['code'=>-6,'message'=>'本团已满'];
        }
        $new_users = User::findOne($userid)->getAttributes(['id','nickname','avatar','phone']);
        $new_users['captain']=false;
        $model->users=json_encode(array_merge($users,[$new_users]));
//        $model->users = json_encode(array_merge($users,[[
//            'id'=>$userid,
//            'nickname'=>Yii::$app->user->identity->nickname,
//            'avatar'=>Yii::$app->user->identity->avatar,
//            'captain'=>false,
//            'phone'=>Yii::$app->user->identity->phone
//        ]]));
        if(count($users)==$peoples-1) { //满团改状态标记
            $model->status = 1;
            $model->endtime=date("Y-m-d H:i:s");
        }
        //返回结果
        if($model->save()){
            if(count($users)==$peoples-1){ //满团发券发短信

               $this->IssueCoupons($model->users,$model->goodsid);
            }
            return ['code'=>1,'message'=>'success','data'=>[
                'id'=>$model->id,
                'status'=>$model->status,
                'product'=>$product->toArray(),
                'members'=>json_decode($model->users,true)
            ]];
        }else{
            return ['code'=>0,'message'=>$model->getErrors()];
        }


    }

    public function IssueCoupons($users,$product_id){

        $users = json_decode($users,true);
        foreach($users as $user){
            $userid = $user['id'];

            Yii::$app->queue->push(new IssueCouponsJob([
                'userid' => $userid,
                'goodsid' =>$product_id
            ]));


        }


    }

    function couponifexist($mark_id){
        $database = Yii::$app->mongo->getDatabase();
        $coupon_category_collection = $database->getCollection("coupon")->findOne(['catalog_mark_id'=>$mark_id]);
        if($coupon_category_collection['origin_num'] > $coupon_category_collection['use_num']){
            return true;
        }else{
            return false;
        }
    }

}
